﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XB.Core.MemoryStore.TaskTimer;
using XB.Core.MemoryStore.ModelInterface;

namespace XB.Core.MemoryStore.MemoryStore
{
    public abstract class IncrementalMemoryStore<T, TKey> : IMemoryStore where T : IIncrementalData<TKey>
    {
        protected Dictionary<TKey, T> _store = new Dictionary<TKey, T>();

        private ITaskTimer _timer;
        private long _rowVersion;
        public IncrementalMemoryStore(int interval)
        {
            _timer = new CountdownTimer(interval);
        }

        public abstract int Level { get; }

        public abstract string Name { get; }

        public ITaskTimer Timer
        {
            get
            {
                return _timer;
            }
        }

        public void Refresh()
        {
            LoadDataToMemory();
        }

        public abstract List<T> GetIncrementalData(long rowVersion);

        public virtual void LoadDataToMemory()
        {
            var incrementalDatas = GetIncrementalData(_rowVersion);
            if (incrementalDatas == null || incrementalDatas.Count == 0)
            {
                return;
            }

            var shadowStore = GetShadowStore();
            foreach (var newData in incrementalDatas)
            {
                if (newData is ISoftDelete && ((ISoftDelete)newData).IsDeleted)
                {
                    shadowStore.Remove(newData.ID);
                }
                else
                {
                    shadowStore[newData.ID] = newData;
                }
            }

            _store = shadowStore;
        }

        public Dictionary<TKey, T> GetShadowStore()
        {
            var newStore = new Dictionary<TKey, T>();

            foreach (var kv in _store)
            {
                newStore.Add(kv.Key, kv.Value);
            }

            return newStore;
        }
    }
}
